package com.shukesmart.speech.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioDeviceInfo;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;

@SuppressLint("MissingPermission")

public class microPhoneRecorder extends InputStream {

    private static AudioRecord audioRecord;

    private static microPhoneRecorder is;

    private volatile boolean isStarted = false;

    private volatile boolean isClosed;
    private static Context gContext;
    private static final String TAG = "microPhoneRecorder";

    private microPhoneRecorder() {

    }

    @Override
    public int read() throws IOException {
        return 0;
    }

    @Override
    public int read(byte[] b, int off, int len) {
        if (!isStarted && !isClosed) {
            start(); // 建议在CALLBACK_EVENT_ASR_READY事件中调用。
            isStarted = true;
        }
        try {
            return audioRecord.read(b, off, len);
        } catch (Exception e) {
            Log.e(TAG, e.getClass().getSimpleName(), e);
            throw e;
        }
    }


    public static microPhoneRecorder getInstance(Context context) {
        gContext = context;
        if (is == null) {
            synchronized (microPhoneRecorder.class) {
                if (is == null) {
                    is = new microPhoneRecorder();
                }
            }
        }
        is.isClosed = false;
        return is;
    }

    private void start() {
        Log.i(TAG, " microPhoneRecorder start recoding!");
        if (audioRecord == null) {
            int bufferSize = AudioRecord.getMinBufferSize(16000,
                    AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
            Log.e(TAG, "start: bufferSize=" + bufferSize);
// Force use of the line in mic
            // 尝试获取蓝牙音频源的标识
            audioRecord = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION,
                    16000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);

            //开启蓝牙采集音频
            AudioManager audioManager = (AudioManager) gContext.getSystemService(Context.AUDIO_SERVICE);
            audioManager.setBluetoothScoOn(true);
            audioManager.startBluetoothSco();
            // 选择所需的音频设备
//            for (AudioDeviceInfo device : audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS)) {
//                if (device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP||device.getType() == AudioDeviceInfo.TYPE_BLUETOOTH_SCO) {
//                    Log.i(TAG, "检测到蓝牙耳机: " + device.getType());
//
//
//                    audioRecord.setPreferredDevice(device);
//                    break;
//                }
//            }

        }
        if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
            throw new IllegalStateException(
                    "startRecording() called on an uninitialized AudioRecord." + (audioRecord == null));
        }


        audioRecord.startRecording();
        isStarted = true;

        Log.i(TAG, " microPhoneRecorder start recoding finished");
    }


    /**
     * 关闭录音流
     */
    @Override
    public void close() {
        Log.i(TAG, " microPhoneRecorder close");
        if (audioRecord != null) {
            audioRecord.stop();
            audioRecord.release(); // 程序结束别忘记自行释放
            isStarted = false;
            isClosed = true;
            audioRecord = null;
        }
    }
}
